package com.fowo.api.common.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.experimental.UtilityClass;
import org.springframework.http.HttpStatus;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/** 响应处理工具 */
@UtilityClass
public class ResponseUtils {

    /** 获取当前响应对象 */
    public HttpServletResponse getResponse() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        if (servletRequestAttributes != null) {
            return servletRequestAttributes.getResponse();
        }
        return null;
    }

    /** 设置响应文件下载，提供一个文件名 */
    public void setAttachmentFileName(String filename) {
        setAttachmentFileName(getResponse(), filename);
    }

    /** 设置响应文件下载，提供一个文件名 */
    public static void setAttachmentFileName(HttpServletResponse response, String filename) {
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename, StandardCharsets.UTF_8));
    }

    public static final String CONTENT_TYPE_JSON = "application/json; charset=utf-8";

    /** 发送标准 json 响应 */
    public static void sendJson(Object o) {
        sendJson(HttpStatus.OK, o);
    }

    /** 发送标准 json 响应 */
    public static void sendJson(HttpStatus httpStatus, Object o) {
        HttpServletResponse response = getResponse();
        response.setStatus(httpStatus.value());
        response.setContentType(CONTENT_TYPE_JSON);
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            objectMapper.writeValue(response.getOutputStream(), o);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
